package com.ruoyi.web.controller.rest.user;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.WebServerOrder;
import com.ruoyi.system.domain.WebServerUser;
import com.ruoyi.system.domain.WebUser;
import com.ruoyi.system.service.*;
import io.swagger.annotations.*;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.text.ParseException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 服务预约订单Controller
 * 
 * @author wsliupan@126.com
 * @date 2021-06-23
 */
@Api(tags = "预约单")
@RestController
@RequestMapping("/rest/user/serverOrder")
public class _WebServerOrderController extends BaseController
{

    @Autowired
    private ISysDictTypeService dictTypeService;
    @Autowired
    private IWebServerOrderService webServerOrderService;
    @Autowired
    private IWebServerUserService iWebServerUserService;
    @Autowired
    private IWebUserService iWebUserService;
    @Autowired
    private ISysDeptService iSysDeptService;
    @Autowired
    private ISendMsgServer iSendMsgServer;


    @ApiOperation("预约单列表")
    @GetMapping()
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", value = "用户id", required = true),
            @ApiImplicitParam(name = "status", value = "状态 1已预约 2已完成 3已取消" ,required = true),
    })
    public AjaxResult list(Integer userId,Integer status)
    {
        WebUser userData = iWebUserService.getById(userId);
        if (userData == null) {
            return error(Constants.REQUIRED_FAILD);
        }
        if(status == null){
            return error("请传入状态");
        }
        List<Map<String,Object>> list = webServerOrderService.listMaps(new QueryWrapper<WebServerOrder>()
                .eq("user_id",userId)
                .eq("status",status)
                .select("id,user_id,dept_id,order_no,pre_day,pre_time,recycle_type,status,price").orderByDesc("create_time")
        );
        if(CollectionUtils.isNotEmpty(list)){
            list.forEach(stringObjectMap -> {
                Long deptId= Long.valueOf(stringObjectMap.get("dept_id").toString());
                SysDept dept = iSysDeptService.selectDeptById(deptId);
                stringObjectMap.put("image",dept.getImage());
                stringObjectMap.put("dept_name",dept.getDeptName());
            });
        }

        return AjaxResult.success(list);
    }

    /**
     * 查询服务预约订单列表
     */
    @ApiOperation("预约单详细")
    @GetMapping("/detail/{orderId}")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", value = "用户id", required = true)
    })
    public AjaxResult detail(@PathVariable(value = "orderId") Integer orderId,Integer userId)
    {
        WebUser userData = iWebUserService.getById(userId);
        if (userData == null) {
            return error(Constants.REQUIRED_FAILD);
        }
        Map<String,Object> stringObjectMap = webServerOrderService.getMap(new QueryWrapper<WebServerOrder>()
                .eq("id",orderId)
                .select("id,user_id,dept_id,order_no,pre_day,pre_time,recycle_type,status,price,server_user_id"));
        if(stringObjectMap == null)
            return error("订单不存在");

        String userIdStr = stringObjectMap.get("user_id").toString();
        if(!userIdStr.equals(userData.getId().toString())){
            return error("订单不匹配");
        }
        //预约人
        stringObjectMap.put("realname",userData.getRealname());
        stringObjectMap.put("nickname",userData.getNickname());

        Long deptId= Long.valueOf(stringObjectMap.get("dept_id").toString());
        SysDept dept = iSysDeptService.selectDeptById(deptId);
        stringObjectMap.put("image",dept.getImage());
        stringObjectMap.put("dept_name",dept.getDeptName());
        //服务人员
        stringObjectMap.put("server_user","");
        String server_user_id = (String)stringObjectMap.get("server_user_id");
        if(StringUtils.isNotEmpty(server_user_id)){
            WebServerUser serverUser = iWebServerUserService.getById(server_user_id);
            if(serverUser != null){
                stringObjectMap.put("server_user",serverUser.getRealname());
            }
        }

        return AjaxResult.success(stringObjectMap);
    }


    /**
     * 修改保存服务预约订单
     */
    @ApiOperation(value = "保存预约订单")
    @ApiResponses({
            /*@ApiResponse(code = 200, message = "成功", response = WebServerOrder.class)*/
    })
    @PostMapping("/save")
    public AjaxResult save(@RequestBody WebServerOrder webServerOrder)
    {
        WebUser userData = iWebUserService.getById(webServerOrder.getUserId());
        if (userData == null) {
            return error(Constants.REQUIRED_FAILD);
        }
        if(webServerOrder.getDeptId() == null){
            return error("门店ID不能为空");
        }
        if(webServerOrder.getServerUserId() == null){
            return error("技师不能为空");
        }
        SysDept dept = iSysDeptService.selectDeptById(webServerOrder.getDeptId());
        if(dept == null){
            return error("门店不存在");
        }


        WebServerUser serverUser = iWebServerUserService.getById(webServerOrder.getServerUserId());
        if(serverUser == null || webServerOrder.getDeptId().longValue() != dept.getDeptId().longValue()){
            return error("该门店技师不存在");
        }

        if(StringUtils.isEmpty(webServerOrder.getPreDay())){
            return error("预约日期不能为空");
        }
        if(StringUtils.isEmpty(webServerOrder.getPreTime())){
            return error("预约时间不能为空");
        }
        try {
            webServerOrder.setPreDay(webServerOrder.getPreDay().replace("/","-"));
            webServerOrder.setPreDay(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, DateUtils.parseDate(webServerOrder.getPreDay(),DateUtils.YYYY_MM_DD)));
        } catch (ParseException e) {
            return error("预约日期格式错误，格式为:年-月-日");
        }

        List<String> times = iSysDeptService.selectServerUserTime(webServerOrder.getPreDay(),dept.getDeptId(),Integer.valueOf(webServerOrder.getServerUserId()) , true);
        if(CollectionUtils.isEmpty(times)){
            return error("该技师此时间段已被预约");
        }

        int count = webServerOrderService.count(new QueryWrapper<WebServerOrder>()
                .eq("pre_day",webServerOrder.getPreDay())
                .eq("pre_time",webServerOrder.getPreTime())
                .eq("server_user_id",webServerOrder.getServerUserId())
                .ne("status",3)
        );
        if(count > 0){
            return error("此技师的该时间段已被预约");
        }

        if(userData.getRecycleTypeId() != null){
            webServerOrder.setRecycleTypeId(userData.getRecycleTypeId());
            webServerOrder.setRecycleType(userData.getRecycleType());
        }

        webServerOrder.setOrderNo(StringUtils.seqOrderNum("FA",10));
        webServerOrderService.save(webServerOrder);

        //归属门店判断
        if(userData.getDeptId() == null){
            userData.setDeptId(webServerOrder.getDeptId());
            this.iWebUserService.update(new UpdateWrapper<WebUser>()
                    .eq("id",userData.getId())
                    .set("dept_id",webServerOrder.getDeptId()));
        }

        //发送短信
        String leader = dept.getLeader();
        if(StringUtils.isEmpty(leader))
            leader = "用户";
        String deptName = dept.getDeptName();
        String userName= userData.getNickname()+"_"+userData.getRealname()+" ";
        String time = "技师"+serverUser.getRealname()+"的"+webServerOrder.getPreDay()+" "+webServerOrder.getPreTime();
        iSendMsgServer.sendSms(dept.getPhone(),
                "{\"name\":\""+leader+"\",\"deptName\":\""+deptName+"\",\"leader\":\""+userName+"\",\"time\":\""+time+"\"}");

        Map<String,Object > map = new HashMap<>();
        map.put("id",webServerOrder.getId());
        return AjaxResult.success(map);
    }

    /**
     * 修改保存服务预约订单
     */
    @ApiOperation(value = "取消订单")
    @ApiResponses({
            /*@ApiResponse(code = 200, message = "成功", response = WebServerOrder.class)*/
    })
    @PostMapping("/cancel")
    public AjaxResult cancel(@RequestBody WebServerOrder webServerOrder)
    {
//        WebUser userData = iWebUserService.getById(webServerOrder.getUserId());
//        if (userData == null) {
//            return error(Constants.REQUIRED_FAILD);
//        }
        if(webServerOrder.getId() == null){
            return error(Constants.REQUIRED_FAILD);
        }
        webServerOrder = webServerOrderService.getById(webServerOrder.getId());
        String [] preTimes = webServerOrder.getPreTime().split("-");

        Date preDay = DateUtils.parseDate(webServerOrder.getPreDay()+" "+preTimes[0]+":00");
        if(DateUtils.getNowDate().after(/*DateUtils.addDays(*/preDay/*,1)*/)){
            return error("预约单过了所预约的时间，您当前不能取消");
        }

//        if(webServerOrder.getUserId().longValue() != userData.getId().longValue()){
//            return error(Constants.REQUIRED_FAILD);
//        }

        webServerOrder.setStatus(3);
        webServerOrderService.saveOrUpdate(webServerOrder);

        return AjaxResult.success(webServerOrder.getId());
    }

    @Autowired
    private IWebRecycleTypeService webRecycleTypeService;
}
